<script setup lang="tsx">
import {Timer} from '@/types/twinkle'
import {timerDB} from "@/data/lowdb.ts";

const {
    active,
    allTimes,
    timers,
} = defineProps<{
    active: boolean
    allTimes: string[]
    timers: Timer[]
}>()

function isTimeInPast(time: string) {
    const now = new Date()
    const pastTime = new Date()
    pastTime.setHours(Number(time.split(':')[0]))
    pastTime.setMinutes(Number(time.split(':')[1]))
    pastTime.setSeconds(0)
    return pastTime.getTime() < now.getTime()
}

function calBrightClassName(timeBrights: Timer[], index: number) {
    let classNames = ['brightness', 'noDrag']
    if (isBrightest(timeBrights, index)) {
        classNames.push('brightest')
    } else if (isBrightInPast(timeBrights, index)) {
        classNames.push('passed')
    }
    if (active && isClosest(timeBrights, index)) {
        classNames.push('closest')
    }
    return classNames.join(' ')
}

function isBrightInPast(timeBrights: Timer[], index: number) {
    if (index === timeBrights.length - 1) {
        return false
    }
    const nextTime = timeBrights[index + 1].time
    return isTimeInPast(nextTime)
}

function isClosest(timeBrights: Timer[], index: number) {
    const time = timeBrights[index].time
    if (index === timeBrights.length - 1) {
        return isTimeInPast(time)
    }
    const nextTime = timeBrights[index + 1].time

    return isTimeInPast(time) && !isTimeInPast(nextTime)
}

function isBrightest(timeBrights: Timer[], index: number) {
    return index > 0
        && timeBrights[index].brightness >= timeBrights[index - 1].brightness
        && index < timeBrights.length - 1
        && timeBrights[index].brightness >= timeBrights[index + 1].brightness
}

const changeTime = (e: MouseEvent, index: number) => {
    console.log(index)
    if (e.altKey) {
        timers.splice(index, 1)
        timerDB.write()
        return
    }
    const time = timers[index].time
    const [hours, minutes] = time.split(':').map(Number)
    const newTime = new Date()
    newTime.setHours(hours)
    newTime.setMinutes(minutes)
    if (e.ctrlKey) {
        newTime.setMinutes(newTime.getMinutes() - 15); // 减少 15 分钟
    } else {
        newTime.setMinutes(newTime.getMinutes() + 15); // 增加15分钟
    }
    const hoursStr = String(newTime.getHours()).padStart(2, '0');
    const minutesStr = String(newTime.getMinutes()).padStart(2, '0');
    timers[index].time = `${hoursStr}:${minutesStr}`
    timerDB.write()
}

function updateBrightness(e: MouseEvent, index: number) {
    let brightness = timers[index].brightness
    if (e.ctrlKey) {
        brightness = increaseBrightness(brightness, false)
    } else {
        brightness = increaseBrightness(brightness)
    }
    timers[index].brightness = brightness
    timerDB.write()
}

function increaseBrightness(brightness: number, increase: boolean = true) {
    if (increase) {
        if (brightness === 100) {
            return 100
        } else if (brightness < 2) {
            brightness += 1
        } else if (brightness % 10 === 0 || brightness % 10 === 8) {
            brightness += 2
        } else {
            brightness += 3
        }
    } else {
        if (brightness === 0) {
            return 0
        } else if (brightness <= 2) {
            brightness -= 1
        } else if (brightness % 10 === 0 || brightness % 10 === 2) {
            brightness -= 2
        } else {
            brightness -= 3
        }
    }
    return brightness
}

function makeUpTimer(index: number, time: string) {
    let brightness = 0
    if (index > 0) {
        const inc: boolean = timers[index] > timers[index - 1]
        brightness = increaseBrightness(timers[index - 1].brightness, inc)
    }
    const newTimer: Timer = {time, brightness}
    timers.splice(index, 0, newTimer)
    timerDB.write()
}

const render = () => {
    const t: HTMLElement[] = []
    // 用 tsx 能比较方便同时遍历两个数组，实现更灵活的逻辑
    for (let i = 0, j = 0; i < allTimes.length; i++) {
        const time = allTimes[i]
        const timeBright = timers[j]

        let line: HTMLElement
        if (j === timers.length || time < timeBright.time) {
            line = <div className="line">
              <span className={isTimeInPast(time) ? 'passed noDrag' : 'noDrag'}
                    onClick={() => makeUpTimer(j, time)}
                    style={{cursor: 'pointer'}}
              >
                ---
              </span>
            </div>
        } else if (time === timeBright.time) {
            line = <div className="line">
              <span className={isTimeInPast(time) ? 'passed noDrag' : 'noDrag'}
                    onClick={(e: MouseEvent) => changeTime(e, j - 1)}
                    style={{cursor: 'pointer'}}
              >
                {time}
              </span>
                <span className={calBrightClassName(timers, j)}
                      onClick={(e: MouseEvent) => updateBrightness(e, j - 1)}
                      style={{cursor: 'pointer'}}
                >
                {timeBright.brightness}
              </span>
            </div>
            j++
        } // time 只会 <= timeBright.time
        t.push(line)
    }
    return <>{t}</>
}
</script>

<template>
  <component :is="render()"></component>
</template>

<style scoped lang="stylus">
.line
    font-size 17px
    margin-bottom 5px

    .passed
        color #dedede

    .brightness
        display inline-block
        width 20px
        margin-left 15px
        padding-right 5px
        text-align right
        border-right 2px solid transparent

    .brightest
        color #f9c626

    .closest
        border-right 2px solid red
</style>